package com.mylib.libcore.utils;

/**
 * @author Administrator
 * @date 2020/1/9-17:18
 * @description
 **/

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.OSSDataBean;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * OSS图片上传的管理类
 */

public class OssManager {
    /**
     * 图片上传的地址
     * 问后台要的
     */
    public static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    /**
     * Bucket是OSS上的命名空间
     * 问后台要的
     */
    public static String bucketName = "wandian-bk";

    /**
     * 图片的访问地址的前缀
     * 其实就是： bucketName + endpoint
     */
    public static String prefix = "https://wandian-bk.oss-cn-beijing.aliyuncs.com/";
//
//    /**
//     * 图片保存到OSS服务器的目录，问后台要
//     */
//    public static String dir = "app/";



    private OSS mOSS;

    private static OssManager mInstance;

    public static OssManager getInstance() {
        if (mInstance == null) {
            synchronized (OssManager.class) {
                mInstance = new OssManager();
            }
        }
        return mInstance;
    }

    /**
     * 创建OSS对象
     */
    private OSS getOSS(Context context,String accessKeyId,String accessKeySecret,String securityToken) {
        if (mOSS == null) {
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            OSSLog.enableLog();
            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                    accessKeyId, accessKeySecret, securityToken
            );
            mOSS = new OSSClient(context, endpoint, credentialProvider, conf);
        }
        return mOSS;
    }


    /**
     * 图片上传
     * @param context
     * @param filePath   图片的本地路径
     * @param onUploadListener 回调监听
     */
    public void upload(Context context, OSSDataBean bean, String filePath,String  objKey, int position, final OnUploadListener onUploadListener) {
        Observable.just(context)
                .map(new Function<Context, OSS>() {
                    @Override
                    public OSS apply(Context context) throws Exception {
                        return getOSS(context,bean.getAccessKeyId(),bean.getAccessKeySecret(),bean.getSecurityToken());
                    }
                })
                .map(new Function<OSS, String>() {
                    @Override
                    public String apply(OSS oss) throws Exception {
                        Log.d("Oss-objKey",""+objKey);
                        // 创建上传的对象
                        PutObjectRequest put = new PutObjectRequest(bucketName,objKey,filePath);
                        // 上传的进度回调
                        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                if (onUploadListener == null) return;
                                Log.d("Oss-requestProgress", "currentSize: " + currentSize + " totalSize: " + totalSize);
                                onUploadListener.onProgress(position, currentSize, totalSize);
                            }
                        });
                        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                if (onUploadListener == null)return;
                                Log.d("Oss-requestSuccess","imageUrl=="+ request.getObjectKey()+"=="+prefix +request.getObjectKey());
                                onUploadListener.onSuccess(position, request.getObjectKey(),  prefix +request.getObjectKey());
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                serviceException.printStackTrace();
                                clientException.printStackTrace();
                                Log.d("Oss-requestError","request"+ position+"uploaderror"+serviceException.getErrorCode());
                                if (onUploadListener == null)  return;
                                onUploadListener.onFailure(position);
                            }
                        });
                        return filePath;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();


    }

    public interface OnUploadListener {
        /**
         * 上传的进度
         */
        void onProgress(int position, long currentSize, long totalSize);

        /**
         * 成功上传
         */
        void onSuccess(int position, String uploadPath, String imageUrl);

        /**
         * 上传失败
         */
        void onFailure(int position);
    }

    /**
     * 上传到后台的图片的名称
     */
    public static String getRulesImage(String imgName,String hzm) {
        String generateRandStr = "image/";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return generateRandStr +simpleDateFormat.format(date)+"/"+imgName+ "."+hzm;
    }

    /**
     * 获取文件格式名
     */
    public static String getFormatName(String fileName) {
        //去掉首尾的空格
        fileName = fileName.trim();
        String s[] = fileName.split("\\.");
        if (s.length >= 2) {
            return s[s.length - 1];
        }
        return "";
    }

    /**
     * 收款码存放地址
     */
    public static String getSKMPicPath(String imgPath) {
        return  "wandian/u_"+ AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")+"/skm/t_"+System.currentTimeMillis()+"."+ FileUtil.getExtensionName(imgPath);
    }
    /**
     * 获取头像存放地址
     */
    public static String getHeadPicPath(String imgPath) {
        return  "wandian/u_"+ AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")+"/head/t_"+System.currentTimeMillis()+"."+ FileUtil.getExtensionName(imgPath);
    }
    /**
     * 获取打卡图片存放地址
     */
    public static String getDaKaPicPath(String imgPath) {
        return  "wandian/u_"+ AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")+"/daka/t_"+System.currentTimeMillis()+"."+ FileUtil.getExtensionName(imgPath);
    }
    /**
     * 获取意见反馈图片存放地址
     */
    public static String getSuggestPicPath(String imgPath) {
        return  "wandian/u_"+ AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")+"/suggest/t_"+System.currentTimeMillis()+"."+ FileUtil.getExtensionName(imgPath);
    }
}